/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dhnsoft.shortLink.admin.common.biz.user;

import com.alibaba.fastjson2.JSON;
import com.dhnsoft.shortLink.admin.common.convention.exception.ClientException;
import com.dhnsoft.shortLink.admin.common.convention.result.Results;
import com.dhnsoft.shortLink.admin.config.UserFlowRiskControlConfiguration;
import com.google.common.collect.Lists;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

import static com.dhnsoft.shortLink.admin.common.convention.errorcode.BaseErrorCode.FLOW_LIMIT_ERROR;


/**
 * 用户操作流量风控过滤器
 * 公众号：马丁玩编程，回复：加群，添加马哥微信（备注：link）获取项目资料
 */
@Slf4j
@RequiredArgsConstructor
public class UserFlowRiskControlFilter implements Filter {

    // StringRedisTemplate的实例，用于执行Redis操作，尤其是与字符串相关的操作。
    private final StringRedisTemplate stringRedisTemplate;

    // 用户流量风险控制的配置类实例，通常用于存储如时间窗口、最大访问次数等配置信息。
    private final UserFlowRiskControlConfiguration userFlowRiskControlConfiguration;

    // 保存LUA脚本路径的常量，用于限制用户请求流量。
    private static final String USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH = "lua/user_flow_risk_control.lua";

    // @SneakyThrows注解自动抛出检查型异常，无需显式使用throws声明异常。
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 创建一个用于执行Redis脚本的DefaultRedisScript对象。
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        // 设置Redis脚本的来源，这里是从类路径下加载指定LUA脚本。
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(USER_FLOW_RISK_CONTROL_LUA_SCRIPT_PATH)));
        // 设置脚本执行返回的结果类型，这里是Long类型。
        redisScript.setResultType(Long.class);

        // 从用户上下文获取用户名，如果不存在则使用"other"作为默认值。
        String username = Optional.ofNullable(UserContext.getUsername()).orElse("other");

        Long result;
        try {
            // 执行LUA脚本，传递用户名和配置的时间窗口参数。
            result = stringRedisTemplate.execute(redisScript, Lists.newArrayList(username), userFlowRiskControlConfiguration.getTimeWindow());
        } catch (Throwable ex) {
            // 如果执行LUA脚本出现异常，记录错误并返回限流错误信息。
            log.error("执行用户请求流量限制LUA脚本出错", ex);
            returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException(FLOW_LIMIT_ERROR))));
            return;
        }

        // 如果返回的结果为空或者超出最大访问次数，则返回限流错误信息。
        if (result == null || result > userFlowRiskControlConfiguration.getMaxAccessCount()) {
            returnJson((HttpServletResponse) response, JSON.toJSONString(Results.failure(new ClientException(FLOW_LIMIT_ERROR))));
            return;
        }

        // 如果验证通过，则继续执行过滤器链中的下一个过滤器或目标资源。
        filterChain.doFilter(request, response);
    }

    // 封装向客户端返回JSON格式响应的方法。
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        // 设置响应的字符编码和内容类型。
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        // 使用try-with-resources语句确保PrintWriter在使用后正确关闭。
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);  // 输出JSON字符串。
        }
    }

}
